package cn.itsource.org.controller;

import cn.itsource.org.domain.Department;
import cn.itsource.org.query.DepartmentQuery;
import cn.itsource.org.service.IDepartmentService;
import cn.itsource.basic.utils.AjaxResult;
import cn.itsource.basic.utils.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
/*
    1.所有的方法上面都有 @ResponseBody
        解决方案
            1.把注解@ResponseBody 放到类上面
            2.@RestController  =@Controller + @ResponseBody

    2.restful 请求风格
        @PathVariable：通过 @PathVariable 可以将 URL 中占位符参数绑定到控制器处理方法的入参中：URL 中的 {xxx} 占位符可以通过@PathVariable(“xxx“) 绑定到操作方法的入参中
        @RequestBody:接收一个json对象的数据 转换为Java对象
        注意：如果不加 @RequestBody  对象不能接收数据

 */

@RestController
@RequestMapping("/department")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;

    /**
     * 新增或者修改
     * @param department  如果id为空，则是新增，如果id不为空，则是修改
     * @return  返回成功还是失败
     */
    @PutMapping
    public AjaxResult saveOrUpdate(@RequestBody Department department){

        try {
            if (department.getId()==null){
                departmentService.save(department);
            }else {
                departmentService.update(department);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(e.getMessage());
        }
        return  AjaxResult.me();
    }


    /**
     * 批量删除
     * @param departments
     * @return
     */
    @PostMapping("/batchRemove")
    public AjaxResult batchRemove(@RequestBody List<Department> departments){
        try {
            //批量删除
            departmentService.batchRemove(departments);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            departmentService.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(e.getMessage());
        }
        return  AjaxResult.me();
    }

    @GetMapping("/{id}")
    public Department queryById(@PathVariable("id") Long id){
        return  departmentService.loadById(id);
    }

    @GetMapping
    public List<Department> queryAll(){
        return  departmentService.loadAll();
    }

    @PostMapping
    public PageBean<Department> queryPage(@RequestBody DepartmentQuery query){
        return  departmentService.queryPage(query);
    }


    /**
     * 查询所有的部门(但是返回的结果集是有层次结构的)
     * @return
     */
    @PostMapping("/queryTree")
    public List<Department> queryTree(){
        //查询所有的部门(但是返回的结果集是有层次结构的)
        return departmentService.loadTree();
    }
}
